<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }"
                >首页</el-breadcrumb-item
            >
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>添加商品</el-breadcrumb-item>
        </el-breadcrumb>

        <el-card>
            <!-- 提示信息 -->
            <el-alert
                title="添加商品信息"
                show-icon
                type="info"
                :closable="false"
                center
            ></el-alert>
            <!-- 步骤条 -->
            <el-steps
                :active="activeIndex - 0"
                finish-status="success"
                :space="200"
                align-center
            >
                <el-step title="基本信息"></el-step>
                <el-step title="商品参数"></el-step>
                <el-step title="商品属性"></el-step>
                <el-step title="商品图片"></el-step>
                <el-step title="商品内容"></el-step>
                <el-step title="完成"></el-step>
            </el-steps>
            <!-- 标签页 -->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef">
                <el-tabs
                    :tab-position="'left'"
                    v-model="activeIndex"
                    @tab-click="tabClicked"
                    :before-leave="beforeTabLeave"
                >
                    <el-tab-pane label="基本信息" name="0">
                        <el-form-item label="商品名称" prop="goods_name">
                            <el-input v-model="addForm.goods_name"></el-input>
                        </el-form-item>
                        <el-form-item label="商品价格" prop="goods_price">
                            <el-input v-model="addForm.goods_price"></el-input>
                        </el-form-item>
                        <el-form-item label="商品重量" prop="goods_weight">
                            <el-input v-model="addForm.goods_weight"></el-input>
                        </el-form-item>
                        <el-form-item label="商品数量" prop="goods_number">
                            <el-input v-model="addForm.goods_number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品分类">
                            <el-cascader
                                v-model="addForm.goods_cat"
                                :options="cateList"
                                :props="cascaderProps"
                                @change="handleChange"
                                clearable
                            ></el-cascader>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品参数" name="1">
                        <el-form-item
                            v-for="item in manyData"
                            :key="item.attr_id"
                            :label="item.attr_name"
                        >
                            <el-checkbox-group v-model="item.attr_vals">
                                <el-checkbox
                                    v-for="(value, i) in item.attr_vals"
                                    :key="i"
                                    :label="value"
                                    border
                                ></el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品属性" name="2">
                        <el-form-item
                            v-for="item in onlyData"
                            :key="item.attr_id"
                            :label="item.attr_name"
                        >
                            <el-input v-model="item.attr_vals"></el-input>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品图片" name="3">
                        <el-upload
                            action="http://127.0.0.1:8888/api/private/v1/upload"
                            :on-preview="handlePreview"
                            :on-remove="handleRemove"
                            list-type="picture"
                            :headers="headerObj"
                            :on-success="handleSuccess"
                        >
                            <el-button size="small" type="primary"
                                >点击上传</el-button
                            >
                        </el-upload>
                    </el-tab-pane>
                    <el-tab-pane label="商品内容" name="4">
                        <quill-editor v-model="addForm.goods_introduce" />
                        <el-button
                            type="primary"
                            class="btnAdd"
                            @click="addGoods"
                            >添加商品</el-button
                        >
                    </el-tab-pane>
                </el-tabs>
            </el-form>
        </el-card>

        <!-- 预览图片的对话框 -->
        <el-dialog title="图片预览" :visible.sync="previewVisiable" width="50%">
            <img :src="previewPath" alt="" class="previewImg" />
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            activeIndex: "0",
            addForm: {
                goods_name: "",
                goods_price: null,
                goods_weight: null,
                goods_number: null,
                // 商品分类
                goods_cat: [],
                // 商品图片
                pics: [],
                // 商品介绍
                goods_introduce: "",
                // 商品参数
                attrs: [],
            },
            addFormRules: {
                goods_name: [
                    {
                        required: true,
                        message: "请输入商品名称",
                        trigger: "blur",
                    },
                ],
                goods_price: [
                    {
                        required: true,
                        message: "请输入商品价格",
                        trigger: "blur",
                    },
                ],
                goods_weight: [
                    {
                        required: true,
                        message: "请输入商品重量",
                        trigger: "blur",
                    },
                ],
                goods_number: [
                    {
                        required: true,
                        message: "请输入商品数量",
                        trigger: "blur",
                    },
                ],
            },
            cascaderProps: {
                expandTrigger: "hover",
                label: "cat_name",
                value: "cat_id",
                children: "children",
            },
            cateList: [],
            manyData: [],
            onlyData: [],
            headerObj: {
                Authorization: sessionStorage.getItem("token"),
            },
            previewVisiable: false,
            previewPath: "",
        };
    },
    created() {
        this.getCateList();
    },
    methods: {
        // tab被选中时执行
        async tabClicked() {
            // 判断是动态参数还是静态参数
            if (this.activeIndex == "1") {
                const { data: res } = await this.$http.get(
                    `categories/${this.cateId}/attributes`,
                    {
                        params: {
                            sel: "many",
                        },
                    }
                );
                if (res.meta.status != 200) {
                    return this.$message.error("获取动态参数失败");
                }

                res.data.forEach((item) => {
                    item.attr_vals = item.attr_vals
                        ? item.attr_vals.split(" ")
                        : [];
                });
                this.manyData = res.data;
                // console.log(this.manyData);
            } else if (this.activeIndex == "2") {
                const { data: res } = await this.$http.get(
                    `categories/${this.cateId}/attributes`,
                    {
                        params: {
                            sel: "only",
                        },
                    }
                );
                if (res.meta.status != 200) {
                    return this.$message.error("获取静态参数失败");
                }
                this.onlyData = res.data;
                // console.log(this.onlyData);
            }
        },
        handleChange() {},
        async getCateList() {
            const { data: res } = await this.$http.get("categories");
            if (res.meta.status != 200) {
                return this.$message.error("获取分类列表失败");
            }
            this.cateList = res.data;
            // console.log(res.data);
        },
        // tab栏切换之前执行
        beforeTabLeave(activeName, oldActiveName) {
            if (this.addForm.goods_cat.length !== 3) {
                this.$message.error("请先选择商品分类");
                return false;
            }
        },
        // 图片预览
        handlePreview(file) {
            this.previewVisiable = true;
            this.previewPath = file.response.data.url;
            // console.log(file);
        },
        // 图片删除
        handleRemove(file) {
            // 获取要删除的图片的临时路径
            const filePath = file.response.data.tmp_path;
            // 从pics数组中，找到这个图片对应的索引值
            const i = this.addForm.pics.findIndex((item) => {
                return item.pic === filePath;
            });
            // 从pics数组中删除
            this.addForm.pics.splice(i, 1);
        },
        // 图片上传成功
        handleSuccess(response) {
            // console.log(response);
            this.addForm.pics.push({
                pic: response.data.tmp_path,
            });
        },
        // 添加商品
        addGoods() {
            this.$refs.addFormRef.validate(async (valid) => {
                if (!valid) {
                    return;
                }

                /**
                 * 准备请求前的数据
                 */
                // 处理分类列表数据
                this.addForm.goods_cat = this.addForm.goods_cat.join(",");

                // 处理参数
                this.manyData.forEach((item) => {
                    this.addForm.attrs.push({
                        attr_id: item.attr_id,
                        attr_value: item.attr_vals.join(" "),
                    });
                });
                this.onlyData.forEach((item) => {
                    this.addForm.attrs.push({
                        attr_id: item.attr_id,
                        attr_value: item.attr_vals,
                    });
                });
                console.log(this.addForm);

                // 发送请求
                const { data: res } = await this.$http.post(
                    "goods",
                    this.addForm
                );

                if (res.meta.status != 201) {
                    return this.$message.error("添加商品失败");
                }

                this.$message.success("添加商品成功");
                this.$router.push("/goods");
            });
        },
    },
    computed: {
        cateId: function () {
            return this.addForm.goods_cat.length === 3
                ? this.addForm.goods_cat[2]
                : null;
        },
    },
};
</script>

<style lang="less" scoped>
.el-checked {
    margin: 0 10px 0 0 !important;
}
.previewImg {
    width: 100%;
}
.btnAdd {
    margin-top: 15px;
}
</style>